import { store } from "@/store";
import { defineStore } from "pinia";
import { getLogin } from "@/api/user";
import { resetRouter } from "@/router";
import { clearStore, setStore } from "@/utils/localStorage";
import { setToken } from "@/utils/auth";
export const useUserStore = defineStore({
  id: "user-store",
  state: () => ({
    // 前端生成的验证码（按实际需求替换）
    verifyCode: ""
  }),
  actions: {
    /** 存储前端生成的验证码 */
    setVerifyCode(verifyCode: string) {
      this.verifyCode = verifyCode;
    },
    /** 登录 */
    loginByUsername(data) {
      return new Promise((resolve, reject) => {
        getLogin(data)
          .then((res) => {
            const { data } = res;
            if (data?.code === 200) {
              setToken("token", data.data.tokenValue);
              setToken("tokenName", data.data.tokenName);
              setStore({ name: "userInfo", content: data.data });
              resolve(data);
            }
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /** 退出登录 */
    logout() {
      clearStore({});
      resetRouter();
    }
  }
});

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store);
}
